package com.yoshino.leetcode.improve40.sixteenth;

import java.util.LinkedList;
import java.util.Queue;

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Codec {

    // 层序遍历，用，隔开，反序列化快
    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        if (root == null) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            if (cur != null) {
                sb.append(cur.val);
                queue.add(cur.left);
                queue.add(cur.right);
            } else {
                sb.append(" ");
            }
            sb.append(",");
        }
        return sb.toString();
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        if (data == null) {
            return null;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        String[] split = data.split(",");
        TreeNode root = new TreeNode(Integer.parseInt(split[0]));
        queue.add(root);
        for (int i = 1; i < split.length; i+=2) {
            TreeNode cur = queue.poll();
            if (!" ".equals(split[i])) {
                cur.left = new TreeNode(Integer.parseInt(split[i]));
                queue.add(cur.left);
            }
            if (!" ".equals(split[i + 1])) {
                cur.right = new TreeNode(Integer.parseInt(split[i + 1]));
                queue.add(cur.right);
            }
        }
        return root;
    }
}

// Your Codec object will be instantiated and called as such:
// Codec ser = new Codec();
// Codec deser = new Codec();
// TreeNode ans = deser.deserialize(ser.serialize(root));